package com.camel;

import java.io.FileOutputStream;
import java.util.Map;

import javax.activation.DataHandler;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class MailProcessor implements Processor {

	@Override
	public void process(Exchange exchange) throws Exception {
		Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
		if (attachments.size() > 0) {
			for (String name : attachments.keySet()) {
				DataHandler dh = attachments.get(name);
				// get the file name
				String filename = dh.getName();
				System.out.println("received file " + filename);
				// get the content and convert it to byte[]
				byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, dh.getInputStream());

				// write the data to a file
				FileOutputStream out = new FileOutputStream(filename);
				out.write(data);
				out.flush();
				out.close();
			}
		}
	}

}
